import { Context } from 'koa';
import { MenuService } from '../../services/system/menuService';
import { createError } from '../../middleware/errorHandler';
import { CreateMenuDto, UpdateMenuDto } from '../../dtos/system/MenuDto';
import { generateResponse } from '../../utils';

export class MenuController {
  private menuService: MenuService;

  constructor() {
    this.menuService = new MenuService();
  }

  // 获取所有菜单
  getMenus = async (ctx: Context): Promise<void> => {
    try {
      let data = ctx.request.body as any
      let users = [] as any
      if (data?.page && data?.limit) {
        // const users = await this.userService.getAllUsers(ctx.request.body.page, ctx.request.body.limit);
        users = await this.menuService.getMenusWithPagination(data.page, data.limit);

      } else {
        users = await this.menuService.getAllMenus();
      }


      generateResponse(ctx, users);
    } catch (error: any) {
      throw createError('获取用户列表失败', 500, error);
    }
  };

  // 根据ID获取菜单
  getMenuById = async (ctx: Context): Promise<void> => {
    try {
      const { id } = ctx.params;
      const menu = await this.menuService.getMenuById(id);
      if (!menu) {
        throw createError('菜单不存在', 404);
      }
      generateResponse(ctx, menu);
    } catch (error: any) {
      if (error.status === 404) throw error;
      throw createError('获取用户信息失败', 500, error);
    }
  };

  // 创建菜单
  createMenu = async (ctx: Context): Promise<void> => {
    try {

      // 从验证中间件获取已验证的数据
      const menuData = ctx.state.validatedData as CreateMenuDto;
      console.log(menuData, 'menuData');
      const menu = await this.menuService.createMenu(menuData);
      generateResponse(ctx, menu, '菜单创建成功');
    } catch (error: any) {

      throw createError('创建菜单失败1', 400, error);
    }
  };

  // 更新菜单
  updateMenu = async (ctx: Context): Promise<void> => {
    try {
      const { id } = ctx.params;
      // 从验证中间件获取已验证的数据
      const menuData = ctx.state.validatedData as UpdateMenuDto;

      const menu = await this.menuService.updateMenu(id, menuData);

      if (!menu) {
        throw createError('菜单不存在', 404);
      }
      generateResponse(ctx, menu, '菜单更新成功');
    } catch (error: any) {
      if (error.status === 404) throw error;
      throw createError('更新菜单失败', 400, error);
    }
  };

  // 删除菜单
  deleteMenu = async (ctx: Context): Promise<void> => {
    try {
      const { id } = ctx.params;
      const result = await this.menuService.deleteMenu(id);

      if (!result) {
        throw createError('菜单不存在', 404);
      }

      generateResponse(ctx, null, '菜单删除成功');
    } catch (error: any) {
      if (error.status === 404) throw error;
      throw createError('删除菜单失败', 500, error);
    }
  };
}